package com.dogsong.liteflow.editor.component;

import com.dogsong.liteflow.editor.constant.ContextConstant;
import com.dogsong.liteflow.editor.slot.DataContext;
import com.yomahub.liteflow.core.NodeBooleanComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

@Component("stringBooleanCmp")
@Slf4j
public class StringBooleanCmp extends NodeBooleanComponent {
    @Override
    public boolean processBoolean() throws Exception {
        DataContext dataContext = this.getContextBean(DataContext.class);
        String str1 = (String) Optional.of(dataContext.getDataMap().get(this.getBindData(ContextConstant.INPUT_1_DATA,
                String.class))).orElseThrow(()->new RuntimeException("上下文中不存在此变量"));
        String str2 = (String) dataContext.getDataMap().get(this.getBindData(ContextConstant.INPUT_2_DATA, String.class));
        String compare = ((Map<String,String>) this.getRequestData()).get(this.getTag());
        switch (compare) {
            case "length>":
                return (str1 == null ? 0 : str1.length()) > str2.length();
            case "length<":
                return (str1 == null ? 0 : str1.length()) < str2.length();
            case "length>=":
                return (str1 == null ? 0 : str1.length()) >= str2.length();
            case "length<=":
                return (str1 == null ? 0 : str1.length()) <= str2.length();
            case "length==":
                return (str1 == null ? 0 : str1.length()) == str2.length();
            case "contains":
                return str1 != null && str1.contains(str2);
            case "notContains":
                return str1 == null || !str1.contains(str2);
            case "isEmpty":
                return StringUtils.isEmpty(str1);
            case "isNotEmpty":
                return StringUtils.isNotEmpty(str1);
            case "equals":
                return StringUtils.equals(str1, str2);
            case "equalsIgnoreCase":
                return StringUtils.equalsIgnoreCase(str1, str2);
            case "startsWith":
                return str1 != null && str1.startsWith(str2);
            case "endsWith":
                return str1 != null && str1.endsWith(str2);
            // 字典序比较
            case "compareTo":
                if (str1 == null && str2 == null) return true;
                if (str1 == null) return false;
                return str1.compareTo(str2) > 0;
            // 忽略大小写的字典序比较
            case "compareToIgnoreCase":
                if (str1 == null && str2 == null) return true;
                if (str1 == null) return false;
                return str1.compareToIgnoreCase(str2) > 0;
            default:
                throw new IllegalArgumentException("不支持的字符串比较操作: " + compare);
        }
    }
}
